<template>
  <el-button type="text" style="padding: 5px" :disabled="time>0" @click.stop="getVerCode">{{ getVerCodeStatus }}
  </el-button>
</template>

<script>
/**
 * @author zhaojiuyi
 * @date 2022/9/12-15:44
 * @version 1.0.0
 */
import api from '@/apis/api'
export default {
  data() {
    return {
      time: 0,
      interval: null, //计时器实例
      phoneRegular: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
    }
  },
  props: ['phoneNumber'],
  computed: {
    //通过vue计算属性改变按钮状态，
    getVerCodeStatus() {
      if (this.time === 0) {
        //清除计时器
        clearInterval(this.interval)
        return "发送验证码"
      }
      return `发送成功(${this.time})`
    }
  },
  methods: {
    async getVerCode() {
      //正则表达式验证手机号合法性，发送手机验证码
      if (this.phoneRegular.test(this.phoneNumber)) {
        const result = await api.getVerCode(this.phoneNumber)
        if (result.code === 200){
          this.$util.successMessage("发送成功")
          this.time = 120
          this.interval = setInterval(()=>{
            this.time--
          },1000)
        }else{
          this.$util.errorMessage(result.msg)
        }
      } else (
        this.$util.errorMessage("请正确填写手机号")
      )
    },
  }
}
</script>
